<?php
namespace App\Models\WeChatOauthHome\Common;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

/**
 * 微信OAuth2.0资源公共管理包
 * Class MiniManageModel
 * @package App\Models\MiniHome\Common
 */
class WeChatOauthManageModel
{
    //小程序 APP_ID
    protected $appId = "";

    //小程序 APP_SECRET
    protected $appSecret = "";

    //小程序用户唯一标识
    protected $openId = "";

    //开放平台用户唯一标识
    protected $unionId = "";

    public function __construct()
    {
        $this->appId = env('WECHAT_OAUTH_APP_ID', '');
        $this->appSecret = env('WECHAT_OAUTH_APP_SECRET', '');
    }

    /**
     * 获取AccessToken
     * @return string
     * @throws \Exception
     */
    public function getAccessToken($code) {
        try {
            $appId = env('WECHAT_OAUTH_APP_ID', '');
            $appSecret = env('WECHAT_OAUTH_APP_SECRET', '');
            $uri = "https://api.weixin.qq.com/sns/oauth2/access_token?";
            $params = [
                'code'          =>  $code,
                'appid'         =>  $appId,
                'secret'        =>  $appSecret,
                'grant_type'    =>  'authorization_code'
            ];
            $relAccessTokenInfo = CurlGet($uri, $params);
            if ($relAccessTokenInfo['code'] != 200) {
                return ModelReturn($relAccessTokenInfo['code'], $relAccessTokenInfo['msg']);
            }
            $accessTokenInfo = json_decode($relAccessTokenInfo['response']['data'], true);
            if (array_key_exists('errcode', $accessTokenInfo) && $accessTokenInfo['errcode'] != 0) {
                return ModelReturn($accessTokenInfo['errcode'], $accessTokenInfo['errmsg']);
            }

            return ModelReturn(RETURN_SUCCESS, 'AccessToken 获取成功', $accessTokenInfo);
        } catch (\Throwable $e) {
            return ModelReturn($e->getCode(), $e->getMessage());
        }
    }

    /**
     * @return string
     */
    public function getUnionId(): string
    {
        return $this->unionId;
    }

    /**
     * @return string
     */
    public function getAppId(): string
    {
        return $this->appId;
    }

    /**
     * @param string $AppId
     */
    public function setAppId(string $appId): void
    {
        $this->appId = $appId;
    }

    /**
     * @return string
     */
    public function getAppSecret(): string
    {
        return $this->appSecret;
    }

    /**
     * @param string $AppSecret
     */
    public function setAppSecret(string $appSecret): void
    {
        $this->appSecret = $appSecret;
    }

    /**
     * @return string
     */
    public function getOpenId() {
        return $this->openId;
    }

    /**
     * @param string $openId
     */
    public function setOpenId(string $openId): void
    {
        $this->openId = $openId;
    }
}